package dao;

import model.TeacherApplication;
import util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class TeacherApplicationDao {

    /**
     * 查询所有学生申请信息，包含学生姓名、奖学金名称、申请状态等
     * @return List<TeacherApplication> - 返回申请列表
     */
    public List<TeacherApplication> getAllApplications() {
        List<TeacherApplication> list = new ArrayList<>();
        // 联表查询applications、student、scholarship，获取完整申请信息
        String sql = "SELECT a.id, a.student_id, s.name AS student_name, sc.name AS scholarship_name, a.status, a.reason, a.file_path " +
                "FROM applications a " +
                "JOIN student s ON a.student_id = s.student_id " +
                "JOIN scholarship sc ON a.scholarship_id = sc.id";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql);
             ResultSet rs = ps.executeQuery()) {

            while (rs.next()) {
                // 打印查询结果调试信息
                System.out.println("申请ID=" + rs.getInt("id") +
                        ", 学生ID=" + rs.getString("student_id") +
                        ", 学生名=" + rs.getString("student_name") +
                        ", 奖学金名=" + rs.getString("scholarship_name") +
                        ", 状态=" + rs.getString("status") +
                        ", 申请理由=" + rs.getString("reason") +
                        ", 文件路径=" + rs.getString("file_path"));

                // 构造TeacherApplication对象封装数据
                TeacherApplication app = new TeacherApplication();
                app.setId(rs.getInt("id"));
                app.setStudentId(rs.getString("student_id"));
                app.setStudentName(rs.getString("student_name"));
                app.setScholarshipName(rs.getString("scholarship_name"));
                app.setStatus(rs.getString("status"));
                app.setReason(rs.getString("reason"));
                app.setFilePath(rs.getString("file_path")); // 文件路径（如果有上传附件）

                list.add(app);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 更新指定申请的状态（如通过、拒绝）
     * @param appId 申请ID
     * @param newStatus 新的状态字符串
     * @return boolean 更新是否成功
     */
    public boolean updateStatus(int appId, String newStatus) {
        String sql = "UPDATE applications SET status = ? WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, newStatus);  // 设置新的状态
            ps.setInt(2, appId);          // 指定申请ID
            return ps.executeUpdate() > 0; // 返回更新是否成功
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
